﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using System.Windows.Input;
using System.Xml.Linq;
using ChongJu.CloudService;
using ChongJu.EventManager;
using ChongJu.GlobalInfo;
using Public.Logger;
using Public.Tools;

namespace ChoJu.Single.DAL
{
    public class UploadDal
    {
        private System.Timers.Timer _timer;
        private CloudService _service;
        private string _tabName;
        private string _today = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");

        public UploadDal()
        {
            _service = new CloudService();
            _tabName = $"tab_info";

            _timer = new System.Timers.Timer(1000 * 60 * 60); //每一小时上传一次
            _timer.Elapsed += _timer_Elapsed;
            _timer.Start();
            _timer_Elapsed(null, null);

            Task.Run(() => CheckHistoryData());
        }

        public void SendInfo(string levCode)
        {
            //先更新（有数据的情况下，更新正常）
            var update = $"UPDATE {_tabName} SET count = count + 1 WHERE levelCode = '{levCode}' AND createTime >= '{_today}'";
            var count = SqliteDal.Instance.ExecuteNonQuery(update) ;

            //更新异常时，则没有数据，则创建新数据
            if (count == 0)
            {
                var add = $"INSERT INTO {_tabName} (LevelCode, Count, IsUpload, CreateTime) VALUES ('{levCode}', 1, 0, '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}')";
                count = SqliteDal.Instance.ExecuteNonQuery (add) ;
            }
        }

        private void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            var today = DateTime.Now.ToString("yyyy-MM-dd 00:00:00");
            var sql = $"SELECT * FROM {_tabName} WHERE createTime >= '{today}'";
            var datas = SqliteDal.Instance.Search<UploadInfoModel>(sql);
            if (datas?.Count > 0 == false)
                return;

            datas.ForEach(data =>
            {
                if (data.Count == 0) //为0则不需要上传
                    return;

                var bol = _service.UploadDataInfoOne(GlobalVar.DeviceID, data.LevelCode, data.Count);
                if (bol == false)
                    return;

                Logger.Info($"{data.LevelCode}_{data.Count}");
                var update = $"UPDATE {_tabName} SET Count = 0, IsUpload = 0 WHERE levelcode = '{data.LevelCode}' AND createTime >= '{today}'";
                var count = SqliteDal.Instance.ExecuteNonQuery(update);
            }); 
        }

        private void CheckHistoryData()
        {
            var sql = $"SELECT * FROM {_tabName} WHERE createTime < '{_today}'";
            var datas = SqliteDal.Instance.Search<UploadInfoModel>(sql);
            if (datas == null) //查询异常则直接跳过
                return;

            bool state = false;
            foreach (var item in datas)
            {
                state = _service.UploadDataInfoOne(GlobalVar.DeviceID, item.LevelCode, item.Count);
                if (state == false)
                    break;
                else
                {
                    var delete = $"DELETE FROM {_tabName} WHERE levelcode = '{item.LevelCode}' AND createtime < '{_today}'";
                    SqliteDal.Instance.ExecuteNonQuery(delete);
                }
            }
        }

    }

    public class UploadInfoModel
    {
        public string LevelCode { get; set; }

        public int Count { get; set; }

        public bool IsUpload { get; set; }

        public DateTime CreateTime { get; set; }
    }
}
